package com.xauto.pioneer.appuser.activity.takeCar;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.xauto.pioneer.appuser.R;
import com.xauto.pioneer.appuser.activity.BaseActivity;
import com.xauto.pioneer.appuser.activity.common.PayUtil;
import com.xauto.pioneer.appuser.activity.common.PromptResultActivity;
import com.xauto.pioneer.appuser.activity.common.WebViewActivity;
import com.xauto.pioneer.appuser.activity.mine.VoucherListActivity;
import com.xauto.pioneer.appuser.adapter.OrderTotalAdapter;
import com.xauto.pioneer.appuser.adapter.PaymentAdapter;
import com.xauto.pioneer.appuser.http.API;
import com.xauto.pioneer.appuser.http.BaseLHttpHandler;
import com.xauto.pioneer.appuser.http.Constants;
import com.xauto.pioneer.appuser.http.LHttpLib;
import com.xauto.pioneer.appuser.interfaces.CarOrderInfoCallBack;
import com.xauto.pioneer.appuser.interfaces.OrdercostInfoCallBack;
import com.xauto.pioneer.appuser.model.BillChargeInfo;
import com.xauto.pioneer.appuser.model.CarOrderInfo;
import com.xauto.pioneer.appuser.model.CheckoutMemberAccountInfo;
import com.xauto.pioneer.appuser.model.ClientSetting;
import com.xauto.pioneer.appuser.model.JSONStatus;
import com.xauto.pioneer.appuser.model.OrderCostInfo;
import com.xauto.pioneer.appuser.model.OrderTotalInfo;
import com.xauto.pioneer.appuser.model.Payment;
import com.xauto.pioneer.appuser.model.VoucherDetailInfo;
import com.xauto.pioneer.appuser.util.DataLoadUtil;
import com.xauto.pioneer.appuser.util.ListViewUtil;
import com.xauto.pioneer.appuser.util.PreferencesUtils;
import com.xauto.pioneer.appuser.util.StringUtils;
import com.xauto.pioneer.appuser.util.TimeUtil;
import com.xauto.pioneer.appuser.view.LoadingDialog;
import com.xauto.pioneer.appuser.view.PromptDialog;
import com.xauto.pioneer.appuser.view.TopBar;

import net.tsz.afinal.FinalDb;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

import static com.xauto.pioneer.appuser.R.id.account_balance_text;

/**
 * 费用结算
 * Created by Ellis.Li on 2017/5/4.
 */

public class OrderCostActivity extends BaseActivity {

    @Bind(R.id.order_submit_date_text)
    TextView orderSubmitDateText;
    @Bind(R.id.order_bill_date_text)
    TextView orderBillDateText;
    @Bind(R.id.car_return_date_text)
    TextView carReturnDateText;
    @Bind(R.id.used_km_text)
    TextView usedKmText;
    @Bind(R.id.used_test_km_text)
    TextView used_test_km_text;
    @Bind(R.id.ordercost_order_state)
    TextView ordercost_order_state;
    @Bind(R.id.ordercost_othercost)
    TextView ordercost_othercost;
    @Bind(R.id.used_km_money_text)
    TextView usedKmMoneyText;
    @Bind(R.id.departure_expense)
    TextView departure_expense;
    @Bind(R.id.enter_expense)
    TextView enter_expense;
    @Bind(R.id.used_time_text)
    TextView usedTimeText;
    @Bind(R.id.used_time_money_text)
    TextView usedTimeMoneyText;
//    @Bind(R.id.used_res_text)
//    TextView usedResText;
//    @Bind(R.id.used_res_money_text)
//    TextView usedResMoneyText;
    @Bind(R.id.punish_money_text)
    TextView punishMoneyText;
    @Bind(R.id.punish_linear)
    LinearLayout punishLinear;
    @Bind(R.id.all_cost_text)
    TextView allCostText;
    @Bind(R.id.expense_cost_text)
    TextView expenseCostText;
    @Bind(R.id.unused_voucher_num_text)
    TextView unusedVoucherNumText;
    @Bind(R.id.voucher_name_text)
    TextView voucherNameText;
    @Bind(R.id.voucher_linear)
    LinearLayout voucherLinear;
    @Bind(account_balance_text)
    TextView accountBalanceText;
    @Bind(R.id.balance_select_img)
    ImageView balanceSelectImg;
    @Bind(R.id.pay_money_text)
    TextView payMoneyText;
    @Bind(R.id.listPayment)
    ListView listPayment;
    @Bind(R.id.tvPayNext)
    TextView tvPayNext;
    @Bind(R.id.mRootScrollView)
    ScrollView mRootScrollView;
    @Bind(R.id.order_web_linear)
    LinearLayout orderWebLinear;
    @Bind(R.id.img_costdetail)
    ImageView img_costdetail;

    @Bind(R.id.topBar)
    TopBar topBar;
    //订单编号
    String car_order_no = "";
    //支付方式code
    String payment_code = "app-alipay";
    //会员优惠券ID
    String voucher_member_id = "";
    //使用账户余额(1-是/0-否) 默认为否
    String is_use_balance_amount = "0";
    //使用账户余额 默认为否
    boolean isUseBalanceAmount = false;
    //订单基本信息
    OrderCostInfo orderCostInfo;
    CarOrderInfo carOrderInfo;
    CheckoutMemberAccountInfo memberAccountInfo;
    //会员优惠券可使用数量
    String voucher_use_count = "";
    //账户余额信息
    private PromptDialog promptDialog;
    /** 支付方式适配器*/
    private PaymentAdapter paymentAdapter;
    int VouchPosition=101;
    String telNumber="";
    boolean ifRunning;
    /**订单费用详情适配器*/
    OrderTotalAdapter orderTotalAdapter;
    /**订单费用详情list*/
    List<OrderTotalInfo> orderTotalInfoList;

    private boolean ifSubmitOrder;
    @Override
    protected int getContentView() {
        return R.layout.ac_order_cost;
    }
    /**
     * 入口
     *
     * @param mContext
     */
    public static void startAction(Context mContext, String car_order_no) {
        Intent intent = new Intent(mContext, OrderCostActivity.class);
        intent.putExtra("car_order_no", car_order_no);
        mContext.startActivity(intent);
    }
    @Override
    protected void initView() {
        //注册EventBus
        EventBus.getDefault().register(this);
        topBar.showView(TopBar.LEFT_IMAGE_BTN, TopBar.TITLE);
        topBar.setImage(TopBar.LEFT_IMAGE_BTN, R.mipmap.ic_common_left);
        topBar.setImage(TopBar.LEFT_IMAGE, R.mipmap.ic_common_left);
        topBar.setText(TopBar.TITLE, "费用结算");
        topBar.setLeftOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        initTelNumber();
    }
    private void initTelNumber(){
        FinalDb finalDb = FinalDb.create(mContext);
        List<ClientSetting> client = finalDb.findAll(ClientSetting.class);
        if (client != null && client.size() >0){
            telNumber = client.get(client.size()- 1).getContact_number();
        }
    }
    @Override
    protected void initData() {
        paymentAdapter = new PaymentAdapter(this, R.layout.item_payment);
        listPayment.setAdapter(paymentAdapter);
        listPayment.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(!paymentAdapter.getDataList().get(position).isChoose) {
                    for (int i = 0; i < paymentAdapter.getDataList().size(); i++) {
                        paymentAdapter.getDataList().get(i).isChoose = false;
                    }
                    paymentAdapter.getDataList().get(position).isChoose = true;
                    paymentAdapter.notifyDataSetChanged();
                    payment_code = paymentAdapter.getDataList().get(position).getPayment_code();
                }
            }
        });
        car_order_no = getIntent().getStringExtra("car_order_no");
        startTimer();
        if(loadingDialog == null) {
            loadingDialog = new LoadingDialog(mContext, "正在结算");
        }

    }
    /**开启等待是否结算成功（订单状态改变）任务*/
    int taskTime = 0;
    private  Timer timer;
    TimerTask mTimerTask;

    private void startTimer(){
        if(timer==null){
            timer = new Timer();
        }
        if(mTimerTask  ==null){
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if(taskTime<=6000){
                               loadOrderDetail();
                                taskTime+=2000;
                                if(!loadingDialog.isShowing()) {
                                    loadingDialog.show();
                                }
                            }else {
                                stopTimer();
                                loadingDialog.dismiss();
                                promptDialog = new PromptDialog(mContext, getString(R.string.notic), getString(R.string.order_cost_message),
                                        getString(R.string.once_order_cost), getString(R.string.phone_help),getString(R.string.dialogpic_nopic), new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        promptDialog.dismiss();
                                        //拼接信息
                                        JSONObject car_order_info = new JSONObject();
                                        try {
                                            Log.e("tag",carOrderInfo.toString());
                                            car_order_info.put("parking_site_no", carOrderInfo.parking_site_info.parking_site_no);
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                        new LHttpLib().OrderCostAgain(mContext, memberId, car_order_no,
                                                car_order_info, new BaseLHttpHandler(mContext, true, true) {
                                                    @Override
                                                    public void onSuccess(JSONStatus jsonStatus) {
                                                        super.onSuccess(jsonStatus);
                                                        startTimer();
                                                    }
                                                    @Override
                                                    public void onFailure(Throwable t, int errorNo, String strMsg) {
                                                        super.onFailure(t, errorNo, strMsg);

                                                    }
                                                });
                                    }
                                }, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        //promptDialog.dismiss();
                                        //联系客服
                                        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+telNumber));
                                        startActivity(intent);
                                    }
                                },true,false);
                                promptDialog.show();
                            }
                        }
                    });
                }
            };
        }
        if(timer != null && mTimerTask != null )
            timer.schedule(mTimerTask,0, 2000);
    }
    /**停止重新结算*/
    private void stopTimer(){
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
        taskTime=0;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }
    @OnClick({R.id.voucher_linear, R.id.balance_select_img, R.id.tvPayNext,R.id.order_web_linear,R.id.img_costdetail})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.voucher_linear:
                //选择卡券
                if (!"0".equals(voucher_use_count)){
                    VoucherListActivity.startAction(OrderCostActivity.this,true,car_order_no,VouchPosition,API.GET_ORDER_VOUCHER_LIST);
                }
                break;
            case R.id.img_costdetail:
                final AlertDialog dialog = new AlertDialog.Builder(mContext).create();
                dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                dialog.show();
                Window window = dialog.getWindow();
                window.getDecorView().setPadding(20, 20, 20, 20);
                window.setGravity(Gravity.CENTER);
                window.setContentView(R.layout.dialog_costlist);
                ListView listView = (ListView)window.findViewById(R.id.dialog_costlist_listview);
                listView.setAdapter(orderTotalAdapter);
                WindowManager.LayoutParams lp = window.getAttributes();
                lp.width = WindowManager.LayoutParams.MATCH_PARENT;
                lp.height = WindowManager.LayoutParams.MATCH_PARENT;
                window.setAttributes(lp);
                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        dialog.dismiss();
                    }
                });
                break;
            case R.id.balance_select_img:
                ifSubmitOrder = false;
                //选择是否使用账户余额
                isUseBalanceAmount = !isUseBalanceAmount;
                is_use_balance_amount = isUseBalanceAmount ? "1" : "0";
                balanceSelectImg.setImageResource(isUseBalanceAmount ? R.mipmap.ic_order_user_balance_checked : R.mipmap.ic_order_user_balance_check);
                if (isUseBalanceAmount){
                    double balance_amount = Double.parseDouble(memberAccountInfo.balance_amount);
                    double total_amount_format = Double.parseDouble(orderCostInfo.total_amount_format);
                    if (balance_amount >= total_amount_format){
                        payMoneyText.setText("￥0.00元");
                    }else {
                        double shifu = total_amount_format-balance_amount;
                        payMoneyText.setText("￥"+StringUtils.getSingleDouble(shifu)+"元");
                    }
                }else {
                    payMoneyText.setText("￥"+orderCostInfo.total_amount_format+"元");
                }
                loadOrdercost();
                break;
            case R.id.tvPayNext:
                //确认支付
                ifSubmitOrder = true;
                loadOrdercost();
                PreferencesUtils.putString(mContext,"Park_NO","0");
                break;
            case R.id.order_web_linear:
                WebViewActivity.startAction(mContext,7);
                break;
        }
    }

    /**
     *加载订单详情信息
     */
//DataLoadUtil.getCarOrderDetail(mContext, car_order_no, new CarOrderInfoCallBack() {
    private LoadingDialog loadingDialog;
    private void loadOrderDetail() {
        DataLoadUtil.getCarOrderDetailOrderRun(true,mContext, car_order_no, new CarOrderInfoCallBack() {
            @Override
            public void getCarOrderInfo(CarOrderInfo carInfo) {
                carOrderInfo = carInfo;
                if(!carOrderInfo.car_order_status_id.equals("22")&&!carOrderInfo.car_order_status_id.equals("13")){
                    ifRunning = true;
                           return;
                        }else{
                            loadOrdercost();
                            stopTimer();
                            loadingDialog.dismiss();
                             ifRunning = false;
                        }
                    }


        });
    }

    /**
     *订单结算
     */
    private void loadOrdercost() {
        DataLoadUtil.getOrdercostRun(true,mContext, car_order_no,payment_code,voucher_member_id,
                is_use_balance_amount, new OrdercostInfoCallBack() {
            @Override
            public void getOrdercostInfo(OrderCostInfo costInfo,CheckoutMemberAccountInfo accountInfo) {
                if(ifSubmitOrder){
                   submitOrder();
                }else{
                    orderTotalInfoList =new ArrayList<>();
                    orderCostInfo = costInfo;
                    memberAccountInfo = accountInfo;
                    orderTotalInfoList = costInfo.order_total_list;
                    orderTotalAdapter = new OrderTotalAdapter(OrderCostActivity.this,R.layout.item_ordertotal);
                    orderTotalAdapter.notifyDataSetChanged();
                    orderTotalAdapter.getDataList().clear();
                    orderTotalAdapter.getDataList().addAll(orderTotalInfoList);
                    orderTotalAdapter.notifyDataSetChanged();
//                used_test_km_text.setText(carOrderInfo.test_total_kilometer+"公里");
                    showOrderCastData();
                    stopTimer();
                    loadingDialog.dismiss();
                    ifRunning = false;
            }
            }
        });

    };

    /**
     * 获取支付订单参数
     */
    private void submitOrder(){
        new LHttpLib().submitCarOrder(mContext, memberId,car_order_no, new BaseLHttpHandler(mContext, true, true) {

            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                String payment_order_param = jsonStatus.data.optString("payment_order_param");
                String payment_order_url = jsonStatus.data.optString("payment_order_url");
                //返回支付参数为空，则默认认为支付成
               if (StringUtils.isEmpty(payment_order_param) || (orderCostInfo != null && Double.parseDouble(orderCostInfo.total_amount_format) == 0)){
                   rechargeSuccess();
               }else {
                   new PayUtil(OrderCostActivity.this, payment_order_param,payment_code);
               }
            }
        });
    }


//    private void checkout() {
//        new LHttpLib().checkoutOrder(mContext, memberId,car_order_no,payment_code,voucher_member_id,is_use_balance_amount, new BaseLHttpHandler(mContext, true, true) {
//            @Override
//            public void onSuccess(JSONStatus jsonStatus) {
//                super.onSuccess(jsonStatus);
//                if(ifSubmitOrder){
//                    submitOrder();
//                }else{
////                    if(!orderCostInfo.car_order_status_id.equals("22")&&!orderCostInfo.car_order_status_id.equals("13")){
////                        ifRunning = true;
////                        return;
////                        //loadOrderDetail();
////                    }else {
////                        showOrderCastData();
////                        stopTimer();
////                        loadingDialog.dismiss();
////                        ifRunning = false;
////                    }
//                    Log.e("tag","chekeout信息 "+jsonStatus.data.optJSONObject("car_order_info"));
//                    payMoneyText.setText("￥"+orderCostInfo.total_amount_format+"元");
//                }
//            }
//        });
//    }

    /**
     * 显示相关数据
     */
    private void showOrderCastData(){
        List<Payment> payments = new Payment().getPaymentListForOnLine(mContext);
        paymentAdapter.getDataList().clear();
        paymentAdapter.getDataList().addAll(payments);
        paymentAdapter.notifyDataSetChanged();
        ListViewUtil.setListViewHeightBasedOnChildren(listPayment);
        if (payments.size() > 0)payment_code = paymentAdapter.getDataList().get(0).getPayment_code();
     //   voucher_use_count =carOrderInfo.member_voucher_info.voucher_useable_count.toString();
        if (!StringUtils.isEmpty(orderCostInfo.order_start_time))
            orderSubmitDateText.setText(TimeUtil.getStrTime(Long.parseLong(orderCostInfo.order_start_time),"yyyy-MM-dd HH:mm"));
        if (!StringUtils.isEmpty(orderCostInfo.order_charge_start_time))
            if(orderCostInfo.order_charge_start_time.equals("0")){
                orderBillDateText.setText("0");
            }else{
            orderBillDateText.setText(TimeUtil.getStrTime(Long.parseLong(orderCostInfo.order_charge_start_time),"yyyy-MM-dd HH:mm"));}
        if (!StringUtils.isEmpty(orderCostInfo.order_charge_end_time))
            carReturnDateText.setText(TimeUtil.getStrTime(Long.parseLong(orderCostInfo.order_charge_end_time),"yyyy-MM-dd HH:mm"));
        BillChargeInfo billing_charge_info = orderCostInfo.billing_charge_info;
        Log.e("tag","orderCostInfo = "+orderCostInfo.toString());
        if (billing_charge_info != null){
            usedKmText.setText(orderCostInfo.billing_charge_info.kilometre+"公里");

            usedKmMoneyText.setText(orderCostInfo.billing_charge_info.total_kilometre+"元");
            usedTimeText.setText(orderCostInfo.billing_charge_info.run_time+"分钟");
            usedTimeMoneyText.setText(orderCostInfo.billing_charge_info.total_run_time+"元");
            ordercost_order_state.setText(orderCostInfo.car_order_status_name);
            ordercost_othercost.setText(orderCostInfo.billing_charge_info.total_run_time+"元");
//            usedResText.setText(carOrderInfo.billing_charge_info.energy+"升");
//            usedResMoneyText.setText(carOrderInfo.billing_charge_info.total_energy+"元");
            /*站点取车还车费用*/
            enter_expense.setText(orderCostInfo.billing_charge_info.enter_expense+"元");
            departure_expense.setText(orderCostInfo.billing_charge_info.departure_expense+"元");
            Double allMoney = 0d;
            try {
                allMoney = Double.parseDouble(orderCostInfo.billing_charge_info.total_kilometre)+
                        Double.parseDouble(orderCostInfo.billing_charge_info.total_run_time)+
                        Double.parseDouble(orderCostInfo.billing_charge_info.total_energy);
            }catch (Exception e){

            }finally {
                expenseCostText.setText(StringUtils.getSingleDouble(allMoney)+"元");
            }
        }
        accountBalanceText.setText("账户余额:"+memberAccountInfo.balance_amount_format);
        punishLinear.setVisibility(View.GONE);
        unusedVoucherNumText.setText(getString(R.string.unused_voucher_num,voucher_use_count));
        if ("0".equals(voucher_use_count)){
            voucherNameText.setText("暂无可用卡券");
            voucherNameText.setTextColor(getResources().getColor(R.color.main_black));
        }else {
            voucherNameText.setText("有"+voucher_use_count+"张可用");
            voucherNameText.setTextColor(getResources().getColor(R.color.main_black));
        }

        payMoneyText.setText("￥"+orderCostInfo.total_amount_format+"元");
        allCostText.setText(orderCostInfo.total_amount_format);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //反注册EventBus
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        loadingDialog.dismiss();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e("tag","timer = "+ifRunning);
    }
    /**
     * 接受支付成功的通知信息
     * @param paymentCode
     */
    public void onEventMainThread(String paymentCode){
        switch (paymentCode){
            //支付宝支付成功
            case Constants.PAY_TYPE_ALIPAY:
                rechargeSuccess();
                break;
            //微信支付成功
            case Constants.PAY_TYPE_WECHAT:
                rechargeSuccess();
                break;
        }
    }
    /**
     * 订单支付成功
     */
    private void  rechargeSuccess(){
//        prompt("订单支付成功");
        //传递到OrderActivity || FoundCarActivity界面用于刷新列表数据
        EventBus.getDefault().post("success");
        finish();
        PromptResultActivity.startAction(OrderCostActivity.this,"成功","支付成功\n欢迎你下次继续使用",Constants.PROMPT_RESULT_SUCCESS);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //选择卡券回调
        if (resultCode == RESULT_OK && requestCode == 1000){
            VouchPosition=data.getIntExtra("VouchPosition",VouchPosition);
            Log.e("1234",String.valueOf(VouchPosition));

            if(VouchPosition!=101){
                VoucherDetailInfo selectedVoucherInfo = (VoucherDetailInfo)data.getSerializableExtra("voucherDetailInfo");
                voucher_member_id = selectedVoucherInfo.voucher_member_id;
                voucherNameText.setText("-"+selectedVoucherInfo.discount_amount);
                voucherNameText.setTextColor(getResources().getColor(R.color.red));
                ifSubmitOrder = false;
                loadOrdercost();
               /* double shifuValue=Double.valueOf(payMoneyText.getText().toString());
                double cardValue=Double.valueOf(selectedVoucherInfo.discount_amount);
                payMoneyText.setText("￥"+StringUtils.getSingleDouble(shifuValue-cardValue)+"元");*/
            }else{
                if ("0".equals(voucher_use_count)){
                    voucherNameText.setText("暂无可用卡券");
                    voucherNameText.setTextColor(getResources().getColor(R.color.main_black));
                    payMoneyText.setText("￥"+orderCostInfo.total_amount_format+"元");
                }else {
                    voucherNameText.setText("有"+voucher_use_count+"张可用");
                    voucherNameText.setTextColor(getResources().getColor(R.color.main_black));
                    payMoneyText.setText("￥"+orderCostInfo.total_amount_format+"元");
                }
            }
        }
    }
}